/**
 * 实时同步测试脚本
 * 用于验证环境切换的立即生效机制
 */

const http = require('http');
const fs = require('fs');
const path = require('path');

// 测试配置
const TEST_CONFIG = {
  host: 'localhost',
  port: 8899, // Whistle 默认端口
  testDomain: 'dgvip360.drivergenius3.com',
  testUrl: 'http://dgvip360.drivergenius3.com/test'
};

// 测试结果
let testResults = [];

/**
 * 测试环境切换的实时性
 */
async function testRealtimeSync() {
  console.log('🚀 开始测试 NoHost 插件实时同步机制...\n');
  
  // 测试1: 检查当前规则状态
  await testCurrentRules();
  
  // 测试2: 模拟环境激活
  await testEnvironmentActivation();
  
  // 测试3: 模拟环境取消激活
  await testEnvironmentDeactivation();
  
  // 测试4: 验证规则立即生效
  await testImmediateEffect();
  
  // 输出测试结果
  printTestResults();
}

/**
 * 测试当前规则状态
 */
async function testCurrentRules() {
  console.log('📋 测试1: 检查当前规则状态');
  
  try {
    const rulesContent = fs.readFileSync(path.join(__dirname, 'rules.txt'), 'utf8');
    const hasActiveRules = rulesContent.includes(TEST_CONFIG.testDomain);
    
    testResults.push({
      test: '当前规则状态',
      status: hasActiveRules ? '✅ 有激活规则' : '❌ 无激活规则',
      details: hasActiveRules ? `找到域名: ${TEST_CONFIG.testDomain}` : '未找到激活的域名规则'
    });
    
    console.log(`   状态: ${hasActiveRules ? '有激活规则' : '无激活规则'}`);
    if (hasActiveRules) {
      console.log(`   找到域名: ${TEST_CONFIG.testDomain}`);
    }
    
  } catch (error) {
    testResults.push({
      test: '当前规则状态',
      status: '❌ 读取规则失败',
      details: error.message
    });
    console.log(`   错误: ${error.message}`);
  }
  
  console.log('');
}

/**
 * 测试环境激活
 */
async function testEnvironmentActivation() {
  console.log('🔌 测试2: 模拟环境激活');
  
  try {
    // 模拟调用激活接口
    const response = await makeApiRequest('/cgi-bin/api/whistle/force-refresh', 'POST');
    
    if (response.success) {
      testResults.push({
        test: '环境激活',
        status: '✅ 激活成功',
        details: `响应时间: ${response.data?.responseTime || 'N/A'}ms`
      });
      console.log(`   状态: 激活成功`);
      console.log(`   响应时间: ${response.data?.responseTime || 'N/A'}ms`);
    } else {
      testResults.push({
        test: '环境激活',
        status: '❌ 激活失败',
        details: response.message || '未知错误'
      });
      console.log(`   状态: 激活失败 - ${response.message}`);
    }
    
  } catch (error) {
    testResults.push({
      test: '环境激活',
      status: '❌ 请求失败',
      details: error.message
    });
    console.log(`   错误: ${error.message}`);
  }
  
  console.log('');
}

/**
 * 测试环境取消激活
 */
async function testEnvironmentDeactivation() {
  console.log('🔌 测试3: 模拟环境取消激活');
  
  try {
    // 模拟调用取消激活接口
    const response = await makeApiRequest('/cgi-bin/api/whistle/force-refresh', 'POST');
    
    if (response.success) {
      testResults.push({
        test: '环境取消激活',
        status: '✅ 取消激活成功',
        details: `响应时间: ${response.data?.responseTime || 'N/A'}ms`
      });
      console.log(`   状态: 取消激活成功`);
      console.log(`   响应时间: ${response.data?.responseTime || 'N/A'}ms`);
    } else {
      testResults.push({
        test: '环境取消激活',
        status: '❌ 取消激活失败',
        details: response.message || '未知错误'
      });
      console.log(`   状态: 取消激活失败 - ${response.message}`);
    }
    
  } catch (error) {
    testResults.push({
      test: '环境取消激活',
        status: '❌ 请求失败',
        details: error.message
    });
    console.log(`   错误: ${error.message}`);
  }
  
  console.log('');
}

/**
 * 测试规则立即生效
 */
async function testImmediateEffect() {
  console.log('⚡ 测试4: 验证规则立即生效');
  
  try {
    // 检查规则文件是否立即更新
    const rulesContent = fs.readFileSync(path.join(__dirname, 'rules.txt'), 'utf8');
    const hasActiveRules = rulesContent.includes(TEST_CONFIG.testDomain);
    
    // 检查文件修改时间
    const stats = fs.statSync(path.join(__dirname, 'rules.txt'));
    const fileAge = Date.now() - stats.mtime.getTime();
    
    testResults.push({
      test: '规则立即生效',
      status: hasActiveRules ? '✅ 规则已生效' : '❌ 规则未生效',
      details: `文件更新时间: ${fileAge}ms 前, 当前状态: ${hasActiveRules ? '有激活规则' : '无激活规则'}`
    });
    
    console.log(`   状态: ${hasActiveRules ? '规则已生效' : '规则未生效'}`);
    console.log(`   文件更新时间: ${fileAge}ms 前`);
    
  } catch (error) {
    testResults.push({
      test: '规则立即生效',
      status: '❌ 检查失败',
      details: error.message
    });
    console.log(`   错误: ${error.message}`);
  }
  
  console.log('');
}

/**
 * 发送API请求
 */
function makeApiRequest(path, method = 'GET') {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: 'localhost',
      port: 8899,
      path: path,
      method: method,
      headers: {
        'Content-Type': 'application/json'
      }
    };
    
    const req = http.request(options, (res) => {
      let data = '';
      
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        try {
          const response = JSON.parse(data);
          resolve(response);
        } catch (error) {
          reject(new Error(`解析响应失败: ${error.message}`));
        }
      });
    });
    
    req.on('error', (error) => {
      reject(new Error(`请求失败: ${error.message}`));
    });
    
    req.end();
  });
}

/**
 * 输出测试结果
 */
function printTestResults() {
  console.log('📊 测试结果汇总:');
  console.log('='.repeat(50));
  
  testResults.forEach((result, index) => {
    console.log(`${index + 1}. ${result.test}`);
    console.log(`   ${result.status}`);
    console.log(`   详情: ${result.details}`);
    console.log('');
  });
  
  const successCount = testResults.filter(r => r.status.includes('✅')).length;
  const totalCount = testResults.length;
  
  console.log(`🎯 总体结果: ${successCount}/${totalCount} 项测试通过`);
  
  if (successCount === totalCount) {
    console.log('🎉 所有测试通过！实时同步机制工作正常！');
  } else {
    console.log('⚠️  部分测试失败，请检查相关配置和日志');
  }
}

// 运行测试
if (require.main === module) {
  testRealtimeSync().catch(console.error);
}

module.exports = { testRealtimeSync };
